package com.suliao.common.util;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.suliao.common.base.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

/**
 * @author： M1nG
 * @since： 2020/10/10 20:52
 * @description： Session工具类
 * @version： 1.0
 */
@Component
@Slf4j
public class SessionUtil {

    @Autowired
    private CryPtoUtil cryPtoUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Value(value = "${spring.session.redis.namespace:suliao:session}")
    private String namespace;


    public UserContext getUserContext(HttpSession session) {
        UserContext userContext = null;
        String userInfo = (String) session.getAttribute("user-info");
        try {
            userContext = JSONUtil.toBean(cryPtoUtil.encrypt(userInfo), UserContext.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取用户失败！返回nulL");
        }
        return userContext;
    }


    public UserContext getUserContext() {
        HttpServletRequest request =
                ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        UserContext userContext = null;
        String userInfo = (String) request.getSession().getAttribute("user-info");
        try {
            if (userInfo != null) {
                userContext = JSONUtil.toBean(cryPtoUtil.encrypt(userInfo), UserContext.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取用户失败！返回nulL");
        }
        return userContext;
    }

    public List<UserContext> getALLUserContext() {
        List<UserContext> userContextList = Lists.newArrayList();
        Set<String> keys = redisUtil.getRedisTemplate().keys(namespace + "*");
        keys.stream().forEach(k -> {
            String userInfo = (String) redisUtil.getValue(k + ":sessions:user-info");
            try {
                userContextList.add(JSONUtil.toBean(cryPtoUtil.encrypt(userInfo), UserContext.class));
            } catch (Exception e) {
                e.printStackTrace();
                log.warn("getALLUserContext error " + e.getMessage());
            }
        });
        return userContextList;
    }


}
